//
//  ZYRecoverPasswordViewModel.m
//  YiLin
//
//  Created by Zyark on 2018/6/13.
//  Copyright © 2018年 Zyark. All rights reserved.
//

#import "ZYRecoverPasswordViewModel.h"
#import "AFNetWorkUtils.h"
#import "ZYUser.h"

@implementation ZYRecoverPasswordViewModel


-(RACCommand *)phoneCommand{
    if(!_phoneCommand){
        @weakify(self);
        _phoneCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
            return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
                @strongify(self);
                [self doRecoverPassword:subscriber];
                return nil;
            }];
        }];
    }
    return _phoneCommand;
}

-(RACCommand *)usernameCheckCommand{
    if(!_usernameCheckCommand){
        @weakify(self);
        _usernameCheckCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
            return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
                @strongify(self);
                [self doProblemRecoverPassword:subscriber withType:ZYRecoverPasswordCheckDataTypeUsername];
                return nil;
            }];
        }];
    }
    return _usernameCheckCommand;
}

-(RACCommand *)problemCheckCommand{
    if(!_problemCheckCommand){
        _problemCheckCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
            @weakify(self);
            return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
                @strongify(self);
                [self doProblemRecoverPassword:subscriber withType:ZYRecoverPasswordCheckDataTypeProblem];
                return nil;
            }];
        }];
    }
    return _problemCheckCommand;
}

-(RACCommand *)problemCommand{
    if(!_problemCommand){
        @weakify(self);
        _problemCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
            return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
                @strongify(self);
                [self doProblemRecoverPassword:subscriber withType:ZYRecoverPasswordCheckDataTypePassword];
                return nil;
            }];
        }];
    }
    return _problemCommand;
}

-(RACCommand *)problemListCommand{
    if(!_problemListCommand){
        @weakify(self);
        _problemListCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
            @strongify(self);
            NSString *url = [NSString stringWithFormat:@"%@%@",ZYAPI_BASE_URL,ZYAPI_USER_QUESTION_URL];
            NSDictionary *params = @{@"username":self.username};
            return [[AFNetWorkUtils racPOSTWithURL:url params:params] map:^id(id value) {
                NSDictionary *data = value;
                NSDictionary *result = [data objectForKey:@"result"];
                NSString *question = @"";
                if([[[ZYChangeLanguage sharedZYChangeLanguage] userLanguage] hasPrefix:@"zh"]){
                    question = [result objectForKey:@"question1"];
                }else{
                    question = [result objectForKey:@"question2"];
                }
                if(NULLString(question)){
                    question = @"";
                }
                return question;
            }];
        }];
    }
    return _problemListCommand;
}

/**
 问题找回密码
 @param subscriber subscriber
 @param type 类型
 */
-(void)doProblemRecoverPassword:(id<RACSubscriber>)subscriber withType:(ZYRecoverPasswordCheckDataType)type{
    BOOL success = [self checkProblemRecoverData:subscriber withType:type];
    if(!success){
        return;
    }
    NSDictionary *params;
    NSString *url = @"";
    if(type == ZYRecoverPasswordCheckDataTypeUsername){
        //校验用户名
        params = @{@"username":self.phone};
        url = [NSString stringWithFormat:@"%@%@",ZYAPI_BASE_URL,ZYAPI_VERIFY_USERNAME_URL];
    }else if(type == ZYRecoverPasswordCheckDataTypeProblem){
        //校验问题
        int type = 0;
        if([[[ZYChangeLanguage sharedZYChangeLanguage] userLanguage] hasPrefix:@"en"]){
            type = 1;
        }
        params = @{@"username":self.phone,@"answer":self.problemAnswer,@"type":[NSNumber numberWithInt:type]};
        url = [NSString stringWithFormat:@"%@%@",ZYAPI_BASE_URL,ZYAPI_VERIFY_PROBLEM_URL];
    }else{
        //校验密码
        params = @{@"username":self.phone,@"answer":self.problemAnswer,@"password":self.password};
        url = [NSString stringWithFormat:@"%@%@",ZYAPI_BASE_URL,ZYAPI_FIND_PASSWORD_BY_PROBLEM_URL];
    }
    [[AFNetWorkUtils racPOSTWithURL:url params:params] subscribeNext:^(id x) {
        RACTuple *tuple = [RACTuple tupleWithObjects:[NSNumber numberWithBool:YES], nil];
        [subscriber sendNext:tuple];
        [subscriber sendCompleted];
    } error:^(NSError *error) {
        [subscriber sendError:error];
        [subscriber sendCompleted];
    }];
}



/**
 手机或邮箱找回密码
 @param subscriber subscriber
 */
-(void)doRecoverPassword:(id<RACSubscriber>)subscriber{
    BOOL success = [self checkData:subscriber withType:_type];
    if(!success){
        return;
    }
    NSDictionary *params;
    NSString *url = @"";
    if(_type == ZYRecoverPasswordTypePhone){
        params = @{@"password":self.password,@"phone":self.phone,@"code":self.code};
        url = [NSString stringWithFormat:@"%@%@",ZYAPI_BASE_URL,ZYAPI_FIND_PASSWORD_BY_PHONE_URL];
    }else{
        params = @{@"password":self.password,@"email":self.phone,@"code":self.code};
        url = [NSString stringWithFormat:@"%@%@",ZYAPI_BASE_URL,ZYAPI_FIND_PASSWORD_BY_EMAIL_URL];
    }
    [[AFNetWorkUtils racPOSTWithURL:url params:params] subscribeNext:^(id x) {
        NSDictionary *responseObject = x;
        [responseObject objectForKey:@"result"];
        RACTuple *tuple = [RACTuple tupleWithObjects:[NSNumber numberWithBool:YES], nil];
        [subscriber sendNext:tuple];
        [subscriber sendCompleted];
    } error:^(NSError *error) {
        [subscriber sendError:error];
        [subscriber sendCompleted];
    }];
}

/**
 手机或邮箱找回密码验证数据
 @param subscriber subscriber
 @param type 类型
 @return 是否成功
 */
-(BOOL)checkData:(id<RACSubscriber>)subscriber withType:(ZYRecoverPasswordType)type{
    if(NULLString(self.phone)){
        NSString *errorInfo = @"";
        if(type == ZYRecoverPasswordTypePhone){
            errorInfo = [self.language getStringByKey:LC_ERROR_PHONE_EMPTY];
        }else{
            errorInfo = [self.language getStringByKey:LC_ERROR_EMAIL];
        }
        [subscriber sendError:[NSErrorHelper createErrorWithErrorInfo:errorInfo]];
        [subscriber sendCompleted];
        return NO;
    }
    if(NULLString(self.code)){
        [subscriber sendError:[NSErrorHelper createErrorWithErrorInfo:[self.language getStringByKey:LC_ERROR_CODE_EMPTY]]];
        [subscriber sendCompleted];
        return NO;
    }
    if(NULLString(self.password)){
        [subscriber sendError:[NSErrorHelper createErrorWithErrorInfo:[self.language getStringByKey:LC_ERROR_PASSWORD_EMPTY]]];
        [subscriber sendCompleted];
        return NO;
    }
    if(![self.password isEqualToString:self.rePassword]){
        [subscriber sendError:[NSErrorHelper createErrorWithErrorInfo:[self.language getStringByKey:LC_ERROR_INCONSISTENT_PASSWORD]]];
        [subscriber sendCompleted];
        return NO;
    }
    if(type == ZYRecoverPasswordTypePhone){
        if(![ZYBasicHelper validateMobile:self.phone]){
            [subscriber sendError:[NSErrorHelper createErrorWithErrorInfo:[self.language getStringByKey:LC_ERROR_PHONE]]];
            [subscriber sendCompleted];
            return NO;
        }
    }else if(type == ZYRecoverPasswordTypeEmail){
        if(![ZYBasicHelper validateEmail:self.phone]){
            [subscriber sendError:[NSErrorHelper createErrorWithErrorInfo:[self.language getStringByKey:LC_ERROR_EMAIL]]];
            [subscriber sendCompleted];
            return NO;
        }
    }
    return YES;
}

/**
 问题找回密码验证数据
 @param subscriber subscriber
 @param type 类型ZYRecoverPasswordCheckDataType
 @return 是否成功
 */
-(BOOL)checkProblemRecoverData:(id<RACSubscriber>)subscriber withType:(ZYRecoverPasswordCheckDataType)type{
    if(NULLString(self.phone)){
        [subscriber sendError:[NSErrorHelper createErrorWithErrorInfo:[self.language getStringByKey:LC_ERROR_USERNAME_EMPTY]]];
        [subscriber sendCompleted];
        return NO;
    }
    if(type == ZYRecoverPasswordCheckDataTypeProblem || type == ZYRecoverPasswordCheckDataTypePassword){
        //答案不能为空
        if(NULLString(self.problemAnswer)){
            [subscriber sendError:[NSErrorHelper createErrorWithErrorInfo:[self.language getStringByKey:LC_ERROR_PROBLEM_EMPTY]]];
            [subscriber sendCompleted];
            return NO;
        }
    }
    if(type == ZYRecoverPasswordCheckDataTypePassword){
        //密码找回
        if(NULLString(self.password)){
            [subscriber sendError:[NSErrorHelper createErrorWithErrorInfo:[self.language getStringByKey:LC_ERROR_PASSWORD_EMPTY]]];
            [subscriber sendCompleted];
            return NO;
        }
//        if(![self.password isEqualToString:self.rePassword]){
//            [subscriber sendError:[NSErrorHelper createErrorWithErrorInfo:[self.language getStringByKey:LC_ERROR_INCONSISTENT_PASSWORD]]];
//            [subscriber sendCompleted];
//            return NO;
//        }
    }
    return YES;
}

@end
